<?php
require_once './libs/common.inc.php';
require_once './database/database.inc.php';

$json = getParam('json', NULL);
if ($json === NULL) {
  header('Content-Type: text/xml');
}

global $weida_pdo;

$action = getParam('action', NULL);
try {
	switch ($action) {
		case 'saveMenus':
			saveMenus($weida_pdo);
			break;
	  case 'getMenus':
      getMenus($weida_pdo);
      break;
    case 'getPage':
      getPage($weida_pdo);
      break;
    case 'savePage':
      savePage($weida_pdo);
      break;
		default:
			break;
	}
} catch (PDOException $e) {
	echo $e->getMessage ();
}

function saveMenus($weida_pdo) {
  $mainMenu = getParam('m', NULL);

  $weida_pdo->beginTransaction();;
  $weida_pdo->exec('DELETE FROM `main_menu`');
  $weida_pdo->exec('INSERT INTO `main_menu` ( id, menu ) VALUES ( null, \'' . $mainMenu . '\' )');
  $weida_pdo->commit();
}

function getMenus($weida_pdo) {
  $stmt = $weida_pdo->prepare('SELECT menu FROM `main_menu`');
  $stmt->execute ();
  if ($stmt->rowCount() == 1) {
    $result = $stmt->fetch(PDO::FETCH_OBJ);
    echo $result->menu;
  }
}

function getPage($weida_pdo) {
  $idx = getParam('idx', 0);
  $lang = getParam('lang', 'cn');

  $stmt = ($lang == 'cn') ? $weida_pdo->prepare('SELECT * FROM `content_cn` WHERE idx = ' . $idx) : $weida_pdo->prepare('SELECT * FROM `content_en` WHERE idx = ' . $idx);
  $stmt->execute ();
  if ($stmt->rowCount() == 1) {
    $result = $stmt->fetch(PDO::FETCH_OBJ);
    echo json_encode($result);
    return;
  }
  echo '';
}

function savePage($weida_pdo) {
  $idx = getParam('idx', 0);
  $lang = getParam('lang', 'cn');
  $page = getParam('page', NULL);
  $page = json_decode($page);
  
  if ($lang == 'cn') {
    $weida_pdo->exec('DELETE FROM `content_cn` WHERE idx = ' . $page->idx);
    $weida_pdo->exec('INSERT INTO `content_cn` ( id, main, side_header, side_dialog, header, idx ) VALUES ( null, \'' . addslashes($page->main) . '\', \'' . addslashes($page->side_header) . '\', \'' . addslashes($page->side_dialog) . '\', \'' . addslashes($page->header)  . '\', \'' . $page->idx . '\' )');
  } else {
    $weida_pdo->exec('DELETE FROM `content_en` WHERE idx = ' . $page->idx);
    $weida_pdo->exec('INSERT INTO `content_en` ( id, main, side_header, side_dialog, header, idx ) VALUES ( null, \'' . addslashes($page->main) . '\', \'' . addslashes($page->side_header) . '\', \'' . addslashes($page->side_dialog) . '\', \'' . addslashes($page->header)  . '\', \'' . $page->idx . '\' )');
  }
}
?>